package com.dmc.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.dmc.conf.AliyunOssConfig;
import com.dmc.service.AliyunOssService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.Date;

@Service
@Slf4j
@Transactional
public class AliyunOssServiceImpl implements AliyunOssService {

    @Autowired
    private AliyunOssConfig aliyunOssConfig;
    /**
     * 斜杠
     */
    private final String FLAG_SLANTING_ROD = "/";
    /**
     * http://
     */
    private final String FLAG_HTTP = "http://";
    /**
     * https://
     */
    private final String FLAG_HTTPS = "https://";
    /**
     * 空字符串
     */
    private final String FLAG_EMPTY_STRING = "";
    /**
     * 点号
     */
    private final String FLAG_DOT = ".";
    /**
     * 缺省的最大上传文件大小：20M
     */
    private final int DEFAULT_MAXIMUM_FILE_SIZE = 20;

    /**
     * 横杠
     */
    private final String FLAG_CROSSBAR = "-";

    @Override
    public String uploadFile(String fileName, String filePath, InputStream inputStream) {
        Assert.isTrue(StringUtils.isNotBlank(fileName) || inputStream != null,"参数错误,文件名称不可为空");
        if(StringUtils.isBlank(filePath)) {
            String dateCategory = DateUtil.format(new Date(), "yyyyMMdd");
            filePath = FLAG_SLANTING_ROD.concat(dateCategory).concat(FLAG_SLANTING_ROD);
        }
        String fileUrl;
        OSSClient ossClient = null;
        String fileNamePre = DateUtil.format(new Date(), "yyyyMMddHHmms");
        fileName = fileNamePre+FLAG_CROSSBAR+fileName;
        try{
            long maxSizeAllowed = getMaximumFileSizeAllowed();
            Assert.isTrue(Long.valueOf(inputStream.available()) <= maxSizeAllowed,"参数错误,文件最大不得超过20M");
            ossClient = new OSSClient(aliyunOssConfig.getEndpoint(),
                    aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());
            if(!filePath.startsWith(FLAG_SLANTING_ROD)) {
                filePath = FLAG_SLANTING_ROD.concat(filePath);
            }
            if(!filePath.endsWith(FLAG_SLANTING_ROD)) {
                filePath = filePath.concat(FLAG_SLANTING_ROD);
            }
            StringBuilder buffer = new StringBuilder();
            buffer.append(aliyunOssConfig.getFileHost()).append(filePath).append(fileName);
            fileUrl = buffer.toString();
            String bucketName = aliyunOssConfig.getBucketName();
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, inputStream));
            ossClient.setBucketAcl(aliyunOssConfig.getBucketName(), CannedAccessControlList.PublicRead);
            if(result != null) {
                log.info("Upload result:{}", result.getETag());
                log.info("Upload file {} successfully.", fileName);
            }
            fileUrl = getHostUrl().concat(fileUrl);
        }catch (Exception e){
            log.error("AliyunOssServiceImpl uploadFile fileName:{}",fileName, e);
            throw new IllegalArgumentException(e.getMessage(),e);
        }finally {
            if(ossClient != null) {
                ossClient.shutdown();
            }
        }
        return fileUrl;
    }

    @Override
    public String uploadFile(String fileName, InputStream inputStream) {
        return uploadFile(fileName,null,inputStream);
    }

    /**
     * 获取最大允许上传文件的大小
     * @return
     */
    private long getMaximumFileSizeAllowed() {
        return DEFAULT_MAXIMUM_FILE_SIZE * 1024L * 1024L;
    }

    /**
     * 获取访问的base地址
     * @return
     */
    private String getHostUrl() {
        String hostUrl = null;
        String endpoint = aliyunOssConfig.getEndpoint();
        String bucketName = aliyunOssConfig.getBucketName();
        if(endpoint.startsWith(FLAG_HTTP)) {
            hostUrl = FLAG_HTTP.concat(bucketName).concat(FLAG_DOT)
                    .concat(endpoint.replace(FLAG_HTTP, FLAG_EMPTY_STRING)).concat(FLAG_SLANTING_ROD);
        } else if (endpoint.startsWith(FLAG_HTTPS)) {
            return FLAG_HTTPS.concat(bucketName).concat(FLAG_DOT)
                    .concat(endpoint.replace(FLAG_HTTPS, FLAG_EMPTY_STRING)).concat(FLAG_SLANTING_ROD);
        }
        return hostUrl;
    }
}
